package com.bbc.action;

import java.util.List;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.bbc.base.BaseAction;
import com.bbc.base.BaseMessage;
import com.bbc.entity.comment.Comment;
import com.bbc.entity.comment.CommentQuery;
import com.bbc.entity.comment.CommentTypeEnum;
import com.bbc.entity.product.Product;
import com.bbc.entity.product.ProductQuery;
import com.bbc.entity.product.ProductShowTypeEnum;
import com.bbc.entity.user.User;
import com.bbc.service.comment.CommentService;
import com.bbc.service.product.ProductService;
import com.bbc.service.type.BbcTypeService;
import com.bbc.service.user.UserService;
import com.bbc.util.DateUtils;
import com.bbc.util.PwdUtils;
import com.bbc.util.UrlUtils;

public class IndexAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private Product product;
	private ProductQuery query;
	private List<Product> products;
	private List<Product> products1;
	private List<Product> products2;
	private Comment comment;
	@Autowired
	private transient ProductService productService;
	@Autowired
	private transient BbcTypeService bbcTypeService;
	@Autowired
	private transient UserService userService;
	@Autowired
	private transient CommentService commentService;
	private User user;
	
	private String key;
	
	private String shareurl;
	
	public String index() {
		isLogin();
		if (query == null) {
			query = new ProductQuery();
		}
		if (StringUtils.isEmpty(query.getOrderBy())) {
			query.setOrderBy(" id desc ");
		}
		if (query.getShowType() == null) {
			query.setShowType(ProductShowTypeEnum.SHOW_USER_SHARE.getKey());
		}
		products = productService.findProduct(query, page, 40);
		CommentQuery cq = new CommentQuery();
		cq.setOrderBy(" comment_id desc ");
		cq.setCommentType(CommentTypeEnum.PRODUCT.getKey());
		Random r = new Random();
		for (Product p:products) {
			cq.setParentId(p.getId());
			p.setComments(commentService.findComment(cq, 0, r.nextInt(4)+2));
		}
		return SUCCESS;
	}
	
	public String detail() {
		if (query!=null&&query.getId()!=null) {
			isLogin();
			product = productService.findProductById(query.getId());
			if (product!=null) {
				CommentQuery cq = new CommentQuery();
				cq.setOrderBy(" comment_id desc ");
				cq.setCommentType(CommentTypeEnum.PRODUCT.getKey());
				Random r = new Random();
				cq.setParentId(product.getId());
				product.setComments(commentService.findComment(cq, 0, r.nextInt(5)+5));
				product.setCreatedStr(DateUtils.getDateStr(product.getCreated()));
				
				// 广告
				ProductQuery pq = new ProductQuery();
				pq.setShowType(ProductShowTypeEnum.SHOW_ADVERTISING.getKey());
				int size = productService.findProductCount(pq);
				products1 = productService.findProduct(pq, r.nextInt(size/3+1), 3);
				
				// 该用户其它分享
				pq = new ProductQuery();
				pq.setShowType(ProductShowTypeEnum.SHOW_USER_SHARE.getKey());
				size = productService.findProductCount(pq);
				products2 = productService.findProduct(pq, r.nextInt(size/4+1), 4);
				
				return "detail";
			} else {
				return index();
			}
		}
		return index();
	}
	
	public String reg() {
		return "reg";
	}
	
	public String doreg() {
		String kaptchaExpected = (String)request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); 
		if (kaptchaExpected!=null&&key!=null&&kaptchaExpected.toLowerCase().equals(key.toLowerCase())) {
			user.setName(user.getMail());
			user.setPwd(PwdUtils.build(user.getPassword()));
			userService.addUser(user);
			return dologin();
		} else {
			setResult("key:false");
			return "reg";
		}
	}
	
	public String login() {
		return "login";
	}
	
	public String dologin() {
		user = userService.login(user);
		if (user == null) {
			BaseMessage m = new BaseMessage();
			m.setSuccess(false);
			m.setCode(104);
			m.setInfo("用户名或密码错误");
			setMsg(m);
			return "login";
		}
		setU(user);
		return "index";
	}
	
	public String share() {
		if (StringUtils.isNotEmpty(shareurl) && isLogin()) {
			String id = UrlUtils.getIdParam(shareurl);
			try {
				productService.addProductFromTBApi(Long.valueOf(id),getU(),ProductShowTypeEnum.SHOW_USER_SHARE.getKey());
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "index";
		} else {
			//TODO
			return "index";
		}
	}
	
	public void addcomment() {
		StringBuilder r = new StringBuilder();
		if (isLogin()&&comment!=null) {
			try {
				comment.setUserId(getU().getId());
				comment.setUserNick(getU().getNick());
				comment.setCommentType(CommentTypeEnum.PRODUCT.getKey());
				int count = commentService.addComment(comment);
				if (count<=0) {
					r.append("[{\"result\":\"false\"}]");
				} else {
					r.append("[{\"result\":\"true\",\"commentId\":"+comment.getCommentId()+",\"userId\":\""+comment.getUserId()+
							"\",\"userNick\":\""+comment.getUserNick()+"\",\"commentType\":\""+comment.getCommentType()+
							"\",\"parentId\":\""+comment.getParentId()+"\",\"commentDetail\":\""+comment.getCommentDetail()+"\"}]");
				}
			} catch (Exception e) {
				e.printStackTrace();
				r.append("[{\"result\":\"false\"}]");
			}
		} else {
			r.append("[{\"result\":\"nologin\"}]");
		}
		try {
			sendMessage(r.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void check() {
		String type = request.getParameter("type");
		String value = request.getParameter(type);
		System.out.println(type+" -- "+value);
		boolean boo = userService.check(type, value);
		try {
			if (boo) {
				sendMessage("[{\"result\":\"false\"}]");
			} else {
				sendMessage("[{\"result\":\"true\"}]");
			}
		} catch (Exception e) {
			try {
				sendMessage("[{\"result\":\"false\"}]");
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}
	
	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public ProductQuery getQuery() {
		return query;
	}

	public void setQuery(ProductQuery query) {
		this.query = query;
	}

	public List<Product> getProducts() {
		return products;
	}

	public void setProducts(List<Product> products) {
		this.products = products;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getShareurl() {
		return shareurl;
	}

	public void setShareurl(String shareurl) {
		this.shareurl = shareurl;
	}

	public Comment getComment() {
		return comment;
	}

	public void setComment(Comment comment) {
		this.comment = comment;
	}
	
	public static void main(String[] args) {
		String s = "SR45f";
		System.out.println(s.toUpperCase());
		Random r = new Random();
		System.out.println(r.nextInt(1));
	}

	public List<Product> getProducts1() {
		return products1;
	}

	public List<Product> getProducts2() {
		return products2;
	}
	
}
